package nl.ruudshuis.data;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nl.ruudshuis.beans.GebruikerBean;
import nl.ruudshuis.dao.VeilingDao;
import nl.ruudshuis.db.DBmanager;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class ToevoegController
 */
public class ToevoegController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String TMP_DIR_PATH = "c:\\tmp";
	private static File tmpDir;
	private static final String DESTINATION_DIR_PATH = "/images";
	private static File destinationDir;
	private String realPath = "";

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if (!tmpDir.isDirectory()) {
			tmpDir.mkdirs();
		}
		realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		destinationDir = new File(realPath);
		destinationDir.mkdirs();

	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ToevoegController() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		VeilingDao veilingDao = new VeilingDao((DBmanager) getServletContext()
				.getAttribute("dbman"));
		HttpSession session = request.getSession();
		GebruikerBean b = (GebruikerBean) session.getAttribute("loggedIn");

		getFormData(request, response, veilingDao, b);

		response.sendRedirect("VeilingController");
	}

	private void getFormData(HttpServletRequest request,
			HttpServletResponse response, VeilingDao veilingDao, GebruikerBean b) {
		String titel = "";
		String omschrijving = "";
		long eindtijd = 0;
		double prijs = 0.0;
		String imgPath = "";
		int userId = b.getId();
		int veilingId = 0;
		boolean isEdit = false;

		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		/*
		 * Set the size threshold, above which content will be stored on disk.
		 */
		fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above
		 * threshold.
		 */
		fileItemFactory.setRepository(tmpDir);

		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			/*
			 * Parse the request
			 */
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				/*
				 * Handle Form Fields.
				 */
				if (item.isFormField()) {

					if (item.getFieldName().equals("vId")) {
						veilingId = Integer.parseInt(item.getString());
					}
					if (item.getFieldName().equals("wijzig")) {
						isEdit = true;
					}
					if (item.getFieldName().equals("titel")) {
						titel = item.getString();
					}
					if (item.getFieldName().equals("omschrijving")) {
						omschrijving = item.getString();
					}
					if (item.getFieldName().equals("prijs")) {
						String prijs1 = item.getString();
						if (prijs1.equals("")) {
							prijs1 = "0.00";
						}
						String doublePrijs = prijs1.replace(',', '.');
						prijs = Double.parseDouble(doublePrijs);
					}
					if (item.getFieldName().equals("eindtijd")) {
						String dagen = item.getString();
						int adagen = Integer.parseInt(dagen);
						int ms = adagen * 24 * 3600 * 1000;
						eindtijd = (System.currentTimeMillis() + ms);
					}

					System.out.println("File Name = " + item.getFieldName()
							+ ", Value = " + item.getString());
				} else {
					// Handle Uploaded files.
					imgPath = item.getName();
					System.out
							.println("Field Name = " + item.getFieldName()
									+ ", File Name = " + item.getName()
									+ ", Content type = "
									+ item.getContentType() + ", File Size = "
									+ item.getSize() + " " + imgPath);
					/*
					 * Write file to the ultimate location.
					 */
					if (!imgPath.equals("")) {
						File file = new File(destinationDir, item.getName());
						item.write(file);
					}
				}
			}
			if (!isEdit) {
				veilingDao.createVeiling(titel, omschrijving, eindtijd, prijs,
						userId, imgPath);
			} else {
				veilingDao.updateVeiling(omschrijving, imgPath, veilingId,
						userId);
			}
		} catch (FileUploadException ex) {
			log("Error encountered while parsing the request", ex);
		} catch (Exception ex) {
			log("Error encountered while uploading file", ex);
		}

	}

}
